package com.zx.chatroom.action;

import com.zx.framework.core.util.FileUtil;
import com.zx.framework.web.action.spring.BaseController;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
@Controller
public class DownloadController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(DownloadController.class);
	
	@Resource
	private String uploadImgPath;
	@Resource
	private String uploadFilePath;
	/**
	 * 附件下载
	 * @param fileName
	 * @param id
	 * @return
	 * @throws IOException
	 */
    @RequestMapping(value="/download/{keyFileName}/{id}"
    		,produces= MediaType.APPLICATION_OCTET_STREAM_VALUE+";charset=UTF-8")
    public void download(@PathVariable("keyFileName")String keyFileName,@PathVariable("id")String id
    		,HttpServletResponse rep) throws IOException {
    	String fileName = URLDecoder.decode(keyFileName, "utf-8");
    	String suff = FileUtil.getFileExtension(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
        OutputStream os = rep.getOutputStream();
        rep.addHeader("Content-Disposition", "attachment;filename="+fileName);
       // headers.setContentDispositionFormData("attachment", fileName);
        File f = new File(uploadFilePath+File.separator+id+suff);
        try{
        	os.write(FileUtil.readFileToByteArray(f));
        	os.flush();
        }finally{
        	if(os !=null){
        		os.close();
        	}
        }
       // return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),
       //                                   headers, HttpStatus.CREATED);
    }

}
